<template>
  <view class="container">
    <view class="gwcHead">
      <view class="flex-y-baseline"
        >共有
        <text class="color-title2 text-bold m-l-4 m-r-4">{{
          cartList.length
        }}</text>
        件商品</view
      >
      <view class="manage" v-if="!isEdit" @click="editOption()">
        <image :src="$util.img('/image/manage.png')" mode=""></image>
        管理
      </view>
      <view class="manage complete" v-else @click="editOption()">完成</view>
    </view>

    <view class="boxPanel" v-if="cartList.length">
      <view class="cartList" v-for="(item, index) in cartList" :key="index">
        <image
          :src="
            item.selected
              ? $util.img('/image/radio2.png')
              : $util.img('/image/radio.png')
          "
          mode=""
          class="radio"
          @click="toggleSelection(item)"
        ></image>
        <view class="goodsList">
          <image
            :src="$util.img(item.sku_image, { size: 'mid' })"
            mode="aspectFill"
            lazy-load
          ></image>
          <view class="goodsinfo">
            <view class="ellipsis-2 name">
              {{ item.goods_name }}
            </view>
            <view class="flex-between">
              <view class="font-36 text-bold c-origin">
                <text class="font-26">￥</text>{{ item.price }}
              </view>
              <view class="quantity-control">
                <view class="btn-minus" @click="valChange(item, 'jian')"
                  >-</view
                >
                <input type="number" v-model="item.num" class="quantity" />
                <view
                  class="btn-plus color-title2"
                  @click="valChange(item, 'add')"
                  >+</view
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <emptyData
      :width="empty.width"
      :height="empty.height"
      :text="empty.text"
      :icon="empty.icon"
      :marginTop="empty.marginTop"
      v-if="cartList.length == 0"
    ></emptyData>

    <!-- 结算 -->
    <view
      class="footer fixfooter"
      :class="{ 'bottom-safe-area': isIphoneX }"
      v-if="!isEdit"
    >
      <view class="flex-y-center">
        <image
          :src="$util.img('/image/radio2.png')"
          mode=""
          class="radio"
          v-if="allSelected"
          @click="toggleAllSelection"
        ></image>
        <image
          :src="$util.img('/image/radio.png')"
          mode=""
          class="radio"
          v-else
          @click="toggleAllSelection"
        ></image>
        <text class="c-8d">全选</text>
      </view>
      <view class="flex">
        <view class="m-r-10">
          <view class="font-24 c-8d"
            >选中 {{ selectedItemCount }} 件 需支付</view
          >
          <view
            class="money c-origin text-bold font-52 flex"
            style="align-items: baseline; margin-top: -16rpx"
          >
            <text class="font-28 c-origin">￥</text>{{ selectedTotalPrice }}
          </view>
        </view>
        <view class="submit" @click="submitOrder">结算</view>
      </view>
    </view>
    <!-- 删除 -->
    <view
      class="footer fixfooter"
      :class="{ 'bottom-safe-area': isIphoneX }"
      v-else
    >
      <view class="flex-y-center">
        <image
          :src="$util.img('/image/radio2.png')"
          mode=""
          class="radio"
          v-if="allSelected"
          @click="toggleAllSelection"
        ></image>
        <image
          :src="$util.img('/image/radio.png')"
          mode=""
          class="radio"
          v-else
          @click="toggleAllSelection"
        ></image>
        <text class="c-8d">全选</text>
      </view>
      <view class="delete" @click="deleteSelectedItems">删除</view>
    </view>
  </view>
</template>

<script>
import emptyData from "@/components/emptyData/emptyData.vue";
export default {
  components: {
    emptyData,
  },
  data() {
    return {
      value: 1,
      isIphoneX: false, //判断手机是否是iphoneX以上
      isEdit: false,
      cartList: [], // 用于存储购物车列表数据
      empty: {
        width: 200,
        height: 138,
        text: "当前购物车是空的",
        icon: "/image/emptyCart.png",
        marginTop: 100,
      },
      selectedTotalPrice: 0,
      selectedItemCount: 0,
      allSelected: true,
    };
  },
  computed: {
    // allSelected() {
    //   return this.cartList.every((item) => item.selected);
    // },
    // selectedItemCount() {
    //   return this.cartList.filter((item) => item.selected).length;
    // },
    // selectedTotalPrice() {
    //   return this.cartList
    //     .filter((item) => item.selected)
    //     .reduce((total, item) => total + item.price * item.num, 0)
    //     .toFixed(2);
    // },
  },
  onLoad() {
    this.token = uni.getStorageSync("token");
    this.isIphoneX = this.$util.uniappIsIPhoneX();
    if (this.token) {
      this.getCartList();
    }
  },
  methods: {
    //结算订单
    submitOrder() {
      if (this.selectedItemCount === 0) {
        this.$util.showToast({ title: "请选择商品" });
        return;
      }
      this.isEdit = false; // 退出编辑模式
      // 遍历购物车，获取选中的商品信息，并传递给结算页面
      var cart_ids = [];
      this.cartList.forEach((item) => {
        if (item.selected) {
          cart_ids.push(item.cart_id);
        }
      });

      if (this.isSub) return;
      this.isSub = true;

      uni.setStorage({
        key: "orderCreateData",
        data: {
          cart_ids: cart_ids.toString(),
        },
        success: () => {
          this.$util.redirectTo("/otherpages/mall/submitOrder");
          this.isSub = false;
        },
      });
    },

    editOption() {
      this.isEdit = !this.isEdit;
      if (this.isEdit) {
        // 进入编辑模式时重置所有商品的选中状态
        // this.cartList.forEach((item) => {
        //   item.selected = false;
        // });
      }
    },
    changeTabs(index) {
      if (this.token == "" || this.token == null)
        return this.$util.redirectTo("/pages/index/index");
      this.current = index;
      this.getCartList();
    },
    getCartList() {
      this.$api.sendRequest({
        url: "/api/cart/goodsLists",
        data: {},
        success: (res) => {
          if (res.code == 0) {
            this.cartList = res.data.map((item) => ({
              ...item,
              selected: true,
            })); // 初始化selected属性为false
            this.calcCartList();
          } else {
            this.$util.showToast({ title: res.message });
          }
        },
      });
    },
    calcCartList() {
      this.selectedTotalPrice = this.cartList
        .filter((item) => item.selected)
        .reduce((total, item) => total + item.price * item.num, 0)
        .toFixed(2);
      this.selectedItemCount = this.cartList
        .filter((item) => item.selected)
        .reduce((total, item) => total + item.num, 0);
      if (this.selectedItemCount == 0) this.allSelected = false;
      else this.allSelected = this.cartList.every((item) => item.selected);
    },
    toggleAllSelection() {
      //   this.cartList.forEach((item) => {
      //     item.selected = !this.allSelected;
      //   });
      this.cartList = this.cartList.map((item) => ({
        ...item,
        selected: !this.allSelected,
      }));
      this.calcCartList();
    },
    deleteSelectedItems() {
      const selectedItemIds = this.cartList
        .filter((item) => item.selected)
        .map((item) => item.cart_id);
      console.log("Selected item IDs:", selectedItemIds);
      if (selectedItemIds.length > 0) {
        this.$api.sendRequest({
          url: "/api/cart/delete",
          data: {
            cart_id: selectedItemIds.join(","),
          },
          success: (res) => {
            if (res.code == 0) {
              this.cartList = this.cartList.filter((item) => !item.selected);
              this.calcCartList();
              this.$util.showToast({ title: "删除成功" });
            } else {
              this.$util.showToast({ title: res.message });
            }
          },
          fail: (err) => {
            this.$util.showToast({ title: "网络错误，请稍后再试" });
          },
        });
      } else {
        this.$util.showToast({ title: "请先选择要删除的商品" });
      }
    },
    toggleSelection(item) {
      item.selected = !item.selected;
      this.calcCartList();
    },
    valChange(item, type) {
      if (type == "add") {
        item.num++;
      } else {
        if (item.num > 1) item.num--;
      }
      console.log("Item quantity changed:", item);

      // 示例：更新购物车中某商品的数量
      this.$api.sendRequest({
        url: "/api/cart/edit",
        data: {
          cart_id: item.cart_id,
          num: item.num,
        },
        success: (res) => {
          if (res.code == 0) {
            //   this.$util.showToast({ title: '数量更新成功' });
            this.calcCartList();
          } else {
            this.$util.showToast({ title: res.msg });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.gwcHead {
  display: flex;
  justify-content: space-between;
  margin: 24rpx 24rpx 24rpx;
  .manage {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 30rpx;
    font-size: 26rpx;
    padding: 10rpx 20rpx;
    image {
      width: 22rpx;
      height: 22rpx;
      margin-right: 10rpx;
    }
  }
}

.complete {
  background: $color-title2 !important;
  color: #fff !important;
  padding: 4rpx 30rpx !important;
}

.cartList {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  .radio {
    width: 35rpx;
    height: 35rpx;
    margin-right: 20rpx;
  }
  .goodsList {
    display: flex;
    box-sizing: border-box;
    align-items: center;
    width: 92%;
    image {
      width: 180rpx;
      height: 180rpx;
      margin-right: 30rpx;
      border-radius: 10rpx;
    }
    .goodsinfo {
      width: 388rpx;
    }
  }
  .name {
    height: 78rpx;
    line-height: 1.4;
    margin-bottom: 20rpx;
  }
}

/* 数量控制 */
.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e7e8eb;
  border-radius: 40rpx;
}

.btn-minus,
.btn-plus {
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  margin: 0 10rpx;
  font-weight: bold;
}

.quantity {
  font-size: 32rpx;
  margin: 0 20rpx;
  text-align: center;
  width: 20rpx;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 24rpx;
  box-sizing: border-box;
  .submit {
    width: 265rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    background-color: $color-title2;
    color: #fff;
    border-radius: 60rpx;
  }
  .radio {
    width: 35rpx;
    height: 35rpx;
    margin-right: 20rpx;
  }
  .delete {
    width: 122rpx;
    height: 52rpx;
    line-height: 52rpx;
    text-align: center;
    border: 1px solid #ff0000;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #ff0000;
  }
}
</style>
